﻿@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
    Layout = null;
}

<link href="~/lib/layui/css/layui.css" rel="stylesheet" />
<script src="~/lib/layui/layui.js"></script>
<script src="~/js/js.cookie.js"></script>
<script src="~/js/moment.js"></script>
<script src="~/lib/jquery/dist/jquery.js"></script>

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Quick Start - Layui</title>
    <!-- 引入 layui.css margin-right:-100px" -->
    <link href="//unpkg.com/layui@2.9.20/dist/css/layui.css" rel="stylesheet">
</head>
<body>
    <div class="layui-bg-gray" style="padding: 16px;" id="Inquire">
        <div class="layui-panel" style="width:100%;">
            <div class="layui-card">
                <div class="layui-card-header">
                    查询条件
                </div>
                @* 主体 *@
                <div class="layui-card-body">
                    <form class="layui-form layui-row layui-col-space16" lay-filter="demo-val-filter" action="">
                        <div class="layui-col-md4">
                            <div class="layui-form-item" style="margin-bottom: 10px;">
                                <label class="layui-form-label">供应商编码</label>
                                <div class="layui-input-block">
                                    <input type="text" id="supplierCoding" lay-verify="required" placeholder="请输入" autocomplete="off" class="layui-input">
                                </div>
                            </div>
                        </div>

                        <div class="layui-col-md4">
                            <div class="layui-form-item" style="margin-bottom: 10px;">
                                <label class="layui-form-label">供应商名称</label>
                                <div class="layui-input-block">
                                    <input type="text" id="supplierName" lay-verify="required" placeholder="请输入" autocomplete="off" class="layui-input">
                                </div>
                            </div>
                        </div>

                        <div class="layui-col-md4">
                            <div class="layui-form-item" style="margin-bottom: 10px;">
                                <label class="layui-form-label">状态</label>
                                <div class="layui-input-block">
                                    <select id="supplierStatus">
                                        <option value="0">请选择</option>
                                        <option value="1">有效</option>
                                        <option value="2">无效</option>
                                    </select>
                                </div>
                            </div>
                        </div>

                        <div class="layui-col-md4">
                            <div class="layui-form-item" style="margin-bottom: 10px;">
                                <label class="layui-form-label">供应商区分</label>
                                <div class="layui-input-block">
                                    <select id="supplierDiff">
                                        <option value="">请选择</option>
                                        <option value="公司">公司</option>
                                        <option value="个人">个人</option>
                                    </select>
                                </div>
                            </div>
                        </div>

                        <div class="layui-col-md4">
                            <div class="layui-form-item" style="margin-bottom: 10px;">
                                <label class="layui-form-label">所在城市</label>
                                <div class="layui-input-block">
                                    <select id="city" name="cityId">
                                    </select>
                                </div>
                            </div>
                        </div>

                        <div class="layui-col-md4"></div>

                        <div class="layui-col-md4">
                            <div class="layui-form-item" style="float:right;margin-top:20px;width:350px">
                                <div class="layui-input-block">
                                    <button type="reset" class="layui-btn layui-btn-primary" style="float:left">重置</button>
                                    <div style="width: 150px; float:right;margin-left:10px">
                                        <button type="submit" id="LookInquire" class="layui-btn layui-bg-blue layui-btn-fluid" lay-submit>查询</button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <div class="layui-bg-gray" style="padding: 16px;">
        <div class="layui-panel">
            <div class="layui-card">
                <div class="layui-card-header">
                    <span style="font:bolder">供应商列表</span>
                    <div style="float:right;">
                        <button type="button" style="margin-right:10px;" class="layui-btn layui-btn-sm layui-icon layui-icon-addition" onclick="location.href='/Supplier/CreateSupplier'">新增供应商</button>
                        <button type="button" class="layui-btn layui-btn-primary layui-btn-sm layui-border layui-icon layui-icon-search" id="Unfold">展开查询</button>
                        <button type="button" class="layui-btn layui-btn-primary layui-btn-sm layui-border layui-icon layui-icon-search" id="Close">关闭查询</button>
                        <button type="button" class="layui-btn layui-btn-primary layui-btn-sm layui-border layui-icon layui-icon-export" id="Export" onclick="ExportSupplier()">导出</button>
                        <!--<button type="button" class="layui-btn layui-btn-primary layui-btn-sm layui-border layui-icon layui-icon-upload" onclick="ImportSupplier()">导入</button>
                        <input type="file" name="file" id="file" value="选择文件"> -->
                        <button type="button" class="layui-btn layui-btn-sm demo-class-accept" lay-options="{accept: 'file'}">
                            <i class="layui-icon layui-icon-upload"></i>
                            导入
                        </button>
                    </div>

                </div>
                <div class="layui-card-body">
                    @* 表格 *@
                    <table class="layui-table">
                        <thead>
                            <tr>
                                <th>序号</th>
                                <th>供应商编码</th>
                                <th>供应商名称</th>
                                <th>供应商类型</th>
                                <th>供应商地址</th>
                                <th>供应商电话</th>
                                <th>所在城市</th>
                                <th>创建时间</th>
                                <th>创建人</th>
                                <th>状态</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody></tbody>
                    </table>
                    <div id="demo-laypage-all"></div>
                </div>
            </div>
        </div>
    </div>


    <script>
        // 使用layui的layer模块
        layui.use(['form', 'table', 'layer'], function () {
            var $ = layui.$;
            var form = layui.form;
            var table = layui.table;
            var laypage = layui.laypage;
            var upload = layui.upload;
            var upload = layui.upload;

            //获取分页数据
            var pageIndex = 1;
            var pageSize = 3;

            $(function () {
                //打开页面隐藏查询条件
                $('#Inquire').toggle();
                //隐藏关闭查询
                $('#Close').hide();
                AcquisitionCity();//物料
                SearchSupplier(pageIndex, pageSize);//工艺路线列表
            })


            // 展开查询
            $('#Unfold').on('click', function () {
                $('#Inquire').show();
                //显示后 隐藏展开查询
                $('#Unfold').hide();
                //显示关闭查询
                $('#Close').show();
            });

            // 关闭查询
            $('#Close').on('click', function () {
                $('#Inquire').hide();
                //关闭后 隐藏关闭查询
                $('#Close').hide();
                //关闭后 显示展开查询
                $('#Unfold').show();
            });

            // 绑定查询按钮点击事件
            $('#LookInquire').on('click', function () {
                SearchSupplier(pageIndex, pageSize);
                return false; // 阻止默认 form 跳转
            });

            //获取城市
            function AcquisitionCity() {
                var obj = {
                    CountryId: 1,
                }
                $.ajax({
                    url: '@ViewBag.RedDragonWrite' + "/api/Suppliers/SearchCity",
                    type: 'GET',
                    data: obj,
                    dataType: 'json',
                    success: res => {
                        console.log(res)
                        var options = '<option value="0">请选择</option>';
                        $.each(res.data, function (index, item) {
                            options += '<option value="' + item.cityId + '">' + item.cityName + '</option>';
                        });
                        $('#city').html(options);
                        form.render('select'); // 更新下拉框渲染
                    }
                });
            }



            //获取供应商列表
            function SearchSupplier(index, size) {
                //获取数据
                var data = {
                    pageIndex: index,
                    pageSize: size,
                    supplierCoding: $('#supplierCoding').val(),
                    supplierName: $('#supplierName').val(),
                    supplierStatus: $('#supplierStatus').val(),
                    supplierDiff: $('#supplierDiff').val(),
                    cityId: $('#city').val() || 0,
                }
                console.log(data);
                var totalCount = 0;//总条数
                var totalPage = 0;//总页数
                //获取
                $.ajax({
                    url: '@ViewBag.RedDragonWrite' + "/api/Suppliers/SearchSupplier",
                    type: 'post',
                    data: JSON.stringify(data),
                    dataType: 'json',
                    contentType: "application/json",
                    success: res => {
                        console.log(res)
                        $("tbody").empty();
                        if (res.data != null) {
                            totalCount = res.data.totalCount;
                            totalPage = res.data.pageCount;
                            $.each(res.data.list, function (index, item) {
                                if (item.createdTime == null) {
                                    item.createdTime = "";
                                }
                                else {
                                    item.createdTime = moment(item.createdTime).format("YYYY-MM-DD HH:mm:ss")
                                }
                                $("tbody").append(`<tr>` +
                                    `<td>${item.supplierId}</td>` +
                                    `<td>${item.supplierCoding}</td>` +
                                    `<td>${item.supplierName}</td>` +
                                    `<td>${item.supplierDiff}</td>` +
                                    `<td>${item.supplierAddress}</td>` +
                                    `<td>${item.supplierPhone}</td>` +
                                    `<td>${item.cityName}</td>` +
                                    `<td>${item.createdTime}</td>` +
                                    `<td>${item.createdOwner}</td>` +
                                    `<td>${item.supplierStatus == 1 ? "有效" : "无效"}</td>` +
                                    `<td><button type="button" class="layui-btn layui-btn-primary layui-btn-xs layui-border layui-icon layui-icon-edit" onclick="UpdateSupplier(${item.supplierId})">编辑</button>` +
                                    `<button type="button" class="layui-btn layui-btn-primary layui-btn-xs layui-border layui-icon layui-icon-delete" lay-on="test-confirm" onclick="DeleteSupplier(${item.supplierId})">删除</button></td>` +
                                    `</tr>`)
                            });
                        }
                        laypage.render({
                            elem: 'demo-laypage-all',
                            curr: data.pageIndex,//当前页
                            limit: data.pageSize,//每页显示条数
                            limits: [3, 6, 9, 12],//每页条数的选择项
                            count: totalCount, // 数据总数，从后端得到
                            first: "首页",
                            prev: "上一页",
                            next: "下一页",
                            last: "尾页",
                            layout: ['count', 'first', 'prev', 'page', 'next', 'last', 'limit', 'skip'], // 自定义布局
                            jump: function (obj, first) {
                                console.log("分页", obj);
                                // 首次不执行
                                if (!first) {
                                    pageIndex = obj.curr;
                                    pageSize = obj.limit;
                                    SearchSupplier(pageIndex, pageSize);
                                }
                            }
                        });
                    }
                });
            }

            //导入供应商
            upload.render({
                elem: '.demo-class-accept', // 绑定多个元素
                url: '@ViewBag.RedDragonWrite' + "/api/Suppliers/ImportSupplier", // 此处配置你自己的上传接口即可
                accept: 'file', // 普通文件
                done: function (res) {
                    layui.layer.msg(res.msg, { icon: 6, time: 1000 });
                    setTimeout(function () {
                        location.reload();//刷新页面
                    }, 1000);
                    console.log(res);
                }
            });
        });

        //删除供应商
        function DeleteSupplier(supplierId) {
            layer.confirm('确认删除数据？', { icon: 3 }, function () {
                $.ajax({
                    url: '@ViewBag.RedDragonWrite' + "/api/Suppliers/DeleteSupplier",
                    type: 'DELETE',
                    data: JSON.stringify({ supplierId: supplierId }),
                    dataType: 'json',
                    contentType: "application/json",
                    success: res => {
                        console.log(res)
                        if (res.code == 0) {
                            layer.msg(res.msg, { icon: 1, time: 1000 });
                            setTimeout(function () {
                                location.reload();//刷新页面
                            }, 1000)
                        }
                        else {
                            layer.msg('删除失败', { icon: 2, time: 1000 });
                        }
                    },
                });
            }, function () {
                layer.msg('取消删除');
            });
        }

        //编辑供应商
        function UpdateSupplier(supplierId) {
            location.href = "/Supplier/UpdateSupplier?supplierId=" + supplierId;
        }

        //导出
        function ExportSupplier() {
            location.href = '@ViewBag.RedDragonWrite' + "/api/Suppliers/ExportSupplier";
        }

        //导入
        function ImportSupplier() {
            console.log($('#file').val())

            // 获取文件输入元素
            var fileInput = $('#file')[0]; // 注意这里加了[0]来获取原生的DOM元素
            if (!fileInput.files.length) {
                console.log('没有选择文件');
                layui.layer.msg('请选择要导入的文件', { icon: 5, time: 1000 });
                return; // 如果没有选择文件，则直接返回
            }
            var file = fileInput.files[0];// 获取第一个文件（假设只选择一个文件）
            var formData = new FormData();// 创建FormData对象
            formData.append('file', file);// 将文件添加到FormData对象中

            // 此处可执行 Ajax 等操作
            $.ajax({
                type: "post",
                url: '@ViewBag.RedDragonWrite' + "/api/Suppliers/ImportSupplier",
                data: formData,
                dataType: "json",
                async: false,
                processData: false,// 告诉jQuery不要处理发送的数据（因为已经通过FormData处理了）
                contentType: false,// 告诉jQuery不要设置Content-Type请求头（因为FormData会自动设置正确的边界字符串）
                beforeSend: function () {
                    // 上传前的回调，可以在这里做一些准备工作，比如显示加载动画
                    layer.load();
                },
                success: res => {
                    // 关闭加载动画
                    layer.closeAll('loading');
                    // 处理响应，例如提示成功信息
                    layui.layer.msg(res.msg, { icon: 6, time: 1000 });
                    setTimeout(function () {
                        location.reload();//刷新页面
                    }, 1000);
                },
                error: function (xhr, status, error) {
                    // 关闭加载动画
                    layer.closeAll('loading');
                    // 处理错误响应
                    layui.layer.msg('导入失败，请检查网络连接或文件格式', { icon: 5, time: 1000 });
                    console.error('Ajax请求失败:', xhr, status, error); // 在控制台输出错误信息，方便调试
                }
            })
        }
    </script>
</body>
</html>
